<?php
declare(strict_types=1);

namespace Service\MessageService;
use Service\BaseService;
use Hyperf\Amqp\Producer;
use Service\Code\Normal;
use App\Model\BbcLogModel\WebApiRequestLog;
use App\Amqp\Producer\WebApiRequestLogMessageProducer;

/**
 * 小程序前端接口日志请求中心
 * @author chenshubo
 */
class WebApiRequestLogService extends BaseService
{
    /**
     * 写入接口日志
     * @param array $param
     */
    public function addLog( array $param)
    {
        $insert = [
            'request_terminal'      => $param['request_terminal'],
            'request_url_hash'      => $param['request_url_hash'],
            'request_url'           => $param['request_url'],
            'request_method'        => $param['request_method'],
            'request_parameters'    => $param['request_parameters'],
            'request_used_time'     => $param['request_used_time'],
            'request_ip'            => $param['request_ip'],
            'response_code'         => $param['response_code'],
            'response_msg'          => $param['response_msg'],
            'response_contents'     => $param['response_contents'],
            'request_time'          => $param['request_time'],
        ];
        WebApiRequestLog::instance()->add($insert);
    }
    
    /**
     * 发布消息队列
     * @param array $msg
     */
    public function publishMsg( array $msg  = [] )
    {
        try {
            $handlerMessage = new WebApiRequestLogMessageProducer($msg);
            $producer = container()->get(Producer::class);
            $result = $producer->produce($handlerMessage,true);
            if( $result ) {
                return Normal::returnCode(Normal::SUC,"发布成功");
            }
            return Normal::returnCode(Normal::FAIL,"操作失败，请稍微再试[100000]");
        } catch ( \Throwable $e ) {
            return Normal::returnCode(Normal::FAIL,"操作失败，请稍微再试[{$e->getMessage()},{$e->getLine()},{$e->getFile()}]");
        }
    }
}